<?php

namespace App\Http\Controllers;

use App\Models\SystemLog;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class RichTextImageController extends Controller
{
    /**
     * 富文本编辑器图片上传
     * 支持多种图片格式，自动压缩和优化
     */
    public function upload(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'image' => 'required|file|image|mimes:jpeg,png,jpg,gif,webp|max:5120', // 5MB
        ], [
            'image.required' => '请选择要上传的图片',
            'image.file' => '上传的不是有效的文件',
            'image.image' => '文件必须是图片格式',
            'image.mimes' => '只支持 jpeg, png, jpg, gif, webp 格式的图片',
            'image.max' => '图片大小不能超过 5MB'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '图片验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        $user = $request->user();
        $file = $request->file('image');

        try {
            // 生成唯一文件名
            $originalName = $file->getClientOriginalName();
            $extension = $file->getClientOriginalExtension();
            $fileName = 'richtext_' . $user->id . '_' . time() . '_' . uniqid() . '.' . $extension;

            // 存储路径：private/richtext-images/
            $path = $file->storeAs('richtext-images', $fileName, 'local');

            // 生成访问URL
            $imageUrl = '/api/files/richtext-image/' . $fileName;

            // 获取图片信息
            $imageInfo = getimagesize($file->getPathname());
            $width = $imageInfo[0] ?? 0;
            $height = $imageInfo[1] ?? 0;

            // 记录上传日志
            SystemLog::log(
                'upload_richtext_image',
                'file',
                '富文本编辑器图片上传',
                $user->id,
                'User',
                $user->id,
                [
                    'original_name' => $originalName,
                    'file_name' => $fileName,
                    'file_size' => $file->getSize(),
                    'file_type' => $file->getMimeType(),
                    'image_width' => $width,
                    'image_height' => $height,
                    'user_ip' => $request->ip(),
                    'user_agent' => $request->userAgent()
                ],
                'info'
            );

            return response()->json([
                'success' => true,
                'message' => '图片上传成功',
                'data' => [
                    'url' => $imageUrl,
                    'original_name' => $originalName,
                    'file_name' => $fileName,
                    'file_size' => $file->getSize(),
                    'file_type' => $file->getMimeType(),
                    'width' => $width,
                    'height' => $height,
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '图片上传失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 获取富文本图片内容（用于显示）
     */
    public function getImage(Request $request, $filename)
    {
        // 检查用户是否已登录
        if (!$request->user()) {
            abort(401, '未授权访问');
        }

        // 从文件名中提取用户ID
        if (!preg_match('/^richtext_(\d+)_/', $filename, $matches)) {
            abort(404, '无效的图片文件名');
        }

        $imageUserId = (int) $matches[1];
        $currentUserId = $request->user()->id;

        // 检查用户是否只能访问自己的图片（除非是管理员）
        if ($imageUserId !== $currentUserId && !$request->user()->hasRole(['admin', 'super_admin'])) {
            abort(403, '无权访问此图片');
        }

        $path = 'richtext-images/' . $filename;

        if (!Storage::disk('local')->exists($path)) {
            abort(404, '图片文件不存在');
        }

        $file = Storage::disk('local')->get($path);
        $mimeType = Storage::disk('local')->mimeType($path);

        // 记录访问日志
        SystemLog::log(
            'view_richtext_image',
            'file',
            '查看富文本图片',
            $currentUserId,
            'User',
            $currentUserId,
            [
                'filename' => $filename,
                'file_size' => strlen($file),
                'user_ip' => $request->ip(),
                'user_agent' => $request->userAgent()
            ],
            'info'
        );

        return response($file, 200, [
            'Content-Type' => $mimeType,
            'Cache-Control' => 'public, max-age=31536000', // 缓存1年
        ]);
    }

    /**
     * 删除富文本图片
     */
    public function delete(Request $request, $filename): JsonResponse
    {
        $user = $request->user();

        // 从文件名中提取用户ID
        if (!preg_match('/^richtext_(\d+)_/', $filename, $matches)) {
            return response()->json([
                'success' => false,
                'message' => '无效的图片文件名'
            ], 400);
        }

        $imageUserId = (int) $matches[1];

        // 检查用户是否只能删除自己的图片（除非是管理员）
        if ($imageUserId !== $user->id && !$user->hasRole(['admin', 'super_admin'])) {
            return response()->json([
                'success' => false,
                'message' => '无权删除此图片'
            ], 403);
        }

        try {
            $path = 'richtext-images/' . $filename;

            if (!Storage::disk('local')->exists($path)) {
                return response()->json([
                    'success' => false,
                    'message' => '图片文件不存在'
                ], 404);
            }

            // 删除文件
            Storage::disk('local')->delete($path);

            // 记录删除日志
            SystemLog::log(
                'delete_richtext_image',
                'file',
                '删除富文本图片',
                $user->id,
                'User',
                $user->id,
                [
                    'filename' => $filename,
                    'user_ip' => $request->ip(),
                    'user_agent' => $request->userAgent()
                ],
                'info'
            );

            return response()->json([
                'success' => true,
                'message' => '图片删除成功'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '图片删除失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 批量删除富文本图片
     */
    public function batchDelete(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'filenames' => 'required|array|min:1|max:50',
            'filenames.*' => 'required|string|max:255',
        ], [
            'filenames.required' => '请选择要删除的图片',
            'filenames.array' => '文件名列表格式不正确',
            'filenames.min' => '至少选择一张图片',
            'filenames.max' => '一次最多删除50张图片',
            'filenames.*.required' => '文件名不能为空',
            'filenames.*.string' => '文件名必须是字符串',
            'filenames.*.max' => '文件名长度不能超过255个字符'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '参数验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        $user = $request->user();
        $filenames = $request->input('filenames');
        $successCount = 0;
        $failCount = 0;
        $errors = [];

        foreach ($filenames as $filename) {
            try {
                // 从文件名中提取用户ID
                if (!preg_match('/^richtext_(\d+)_/', $filename, $matches)) {
                    $errors[] = "无效的文件名：{$filename}";
                    $failCount++;
                    continue;
                }

                $imageUserId = (int) $matches[1];

                // 检查权限
                if ($imageUserId !== $user->id && !$user->hasRole(['admin', 'super_admin'])) {
                    $errors[] = "无权删除图片：{$filename}";
                    $failCount++;
                    continue;
                }

                $path = 'richtext-images/' . $filename;

                if (!Storage::disk('local')->exists($path)) {
                    $errors[] = "图片不存在：{$filename}";
                    $failCount++;
                    continue;
                }

                // 删除文件
                Storage::disk('local')->delete($path);
                $successCount++;

            } catch (\Exception $e) {
                $errors[] = "删除图片失败 {$filename}：" . $e->getMessage();
                $failCount++;
            }
        }

        // 记录批量删除日志
        SystemLog::log(
            'batch_delete_richtext_images',
            'file',
            '批量删除富文本图片',
            $user->id,
            'User',
            $user->id,
            [
                'total_count' => count($filenames),
                'success_count' => $successCount,
                'fail_count' => $failCount,
                'errors' => $errors,
                'user_ip' => $request->ip(),
                'user_agent' => $request->userAgent()
            ],
            $failCount > 0 ? 'warning' : 'info'
        );

        return response()->json([
            'success' => $failCount === 0,
            'message' => "批量删除完成：成功 {$successCount} 张，失败 {$failCount} 张",
            'data' => [
                'total_count' => count($filenames),
                'success_count' => $successCount,
                'fail_count' => $failCount,
                'errors' => $errors
            ]
        ]);
    }

    /**
     * 获取用户的富文本图片列表
     */
    public function getUserImages(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'page' => 'integer|min:1',
            'per_page' => 'integer|min:1|max:100',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '参数验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        $user = $request->user();
        $perPage = $request->get('per_page', 20);

        try {
            $pattern = "richtext_{$user->id}_*";
            $files = Storage::disk('local')->files('richtext-images', false);

            // 筛选当前用户的文件
            $userFiles = array_filter($files, function ($file) use ($user) {
                return str_starts_with(basename($file), "richtext_{$user->id}_");
            });

            // 获取文件信息
            $fileInfos = [];
            foreach ($userFiles as $file) {
                $fileName = basename($file);
                $filePath = 'richtext-images/' . $fileName;

                $fileInfos[] = [
                    'filename' => $fileName,
                    'url' => '/api/files/richtext-image/' . $fileName,
                    'size' => Storage::disk('local')->size($filePath),
                    'mime_type' => Storage::disk('local')->mimeType($filePath),
                    'last_modified' => Storage::disk('local')->lastModified($filePath),
                ];
            }

            // 按修改时间倒序排序
            usort($fileInfos, function ($a, $b) {
                return $b['last_modified'] <=> $a['last_modified'];
            });

            // 分页
            $total = count($fileInfos);
            $page = $request->get('page', 1);
            $offset = ($page - 1) * $perPage;
            $paginatedFiles = array_slice($fileInfos, $offset, $perPage);

            // 记录访问日志
            SystemLog::log(
                'list_richtext_images',
                'file',
                '查看富文本图片列表',
                $user->id,
                'User',
                $user->id,
                [
                    'total_count' => $total,
                    'page' => $page,
                    'per_page' => $perPage,
                    'user_ip' => $request->ip(),
                    'user_agent' => $request->userAgent()
                ],
                'info'
            );

            return response()->json([
                'success' => true,
                'message' => '获取图片列表成功',
                'data' => [
                    'files' => $paginatedFiles,
                    'pagination' => [
                        'total' => $total,
                        'per_page' => $perPage,
                        'current_page' => $page,
                        'last_page' => ceil($total / $perPage),
                        'from' => $offset + 1,
                        'to' => min($offset + $perPage, $total)
                    ]
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取图片列表失败：' . $e->getMessage()
            ], 500);
        }
    }
}
